﻿using JLModel;
using Microsoft.Data.Sqlite;
using SqlSugar;
using System.Data;

namespace JLWebBrowser.BLL
{
    public class FavoritesBLL
    {
        /// <summary>
        /// 收藏信息列表
        /// </summary>
        public static List<FavoritesModel> FavoritesList { get; set; }

        public static SqlSugarClient db = null;

        /// <summary>
        /// 获取收藏列表
        /// </summary>
        public static void FavoritesListGet()
        {
            db = new SqlSugarClient(new ConnectionConfig
            {
                DbType = SqlSugar.DbType.Sqlite,//要连接的数据库类型
                ConnectionString = new SqliteConnectionStringBuilder()
                {
                    DataSource = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) + @"\Data.db",
                    Mode = SqliteOpenMode.ReadWriteCreate,
                    //Password = "JLDB"
                }.ToString(),
                IsAutoCloseConnection = true
            });

            try
            {
                //如果不存在创建数据库存在不会重复创建 
                db.DbMaintenance.CreateDatabase();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            //创建表根据实体类
            db.CodeFirst.SetStringDefaultLength(255).InitTables(typeof(FavoritesModel));

            FavoritesList = db.Queryable<FavoritesModel>().ToList();

            FavoritesList = FavoritesList.OrderBy(m => m.FID).ThenBy(m => m.ID).ToList();
        }

        /// <summary>
        /// 添加收藏信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static FavoritesModel FavoritesAdd(FavoritesModel model)
        {
            model.ID = SnowFlakeSingle.Instance.NextId();
            FavoritesModel _m = db.Insertable<FavoritesModel>(model).ExecuteReturnEntity();
            FavoritesList.Add(_m);
            return _m;
        }

        /// <summary>
        /// 更新收藏信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool FavoritesUpdte(FavoritesModel model)
        {
            if (model.ChangeProperty != null && model.ChangeProperty.Count > 0 && db.Updateable<FavoritesModel>(model).UpdateColumns(model.ChangeProperty.ToArray(), true).ExecuteCommand() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除收藏信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool FavoritesDelete(FavoritesModel model)
        {
            if (db.Deleteable<FavoritesModel>().Where(m => m.ID == model.ID).ExecuteCommand() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
